<?php

class DBCache extends DB {
	
	function DBCache($model, $cache_time, $cache_force, $db) {
		$this->db =& $db->db;
		$this->model = str_replace(DS, '.', APP_DIR).'_'.$model;
		$this->cache_time = $cache_time;
		$this->cache_force = $cache_force;
	}

	function query($sql='') {
		$this->cache_db = null;
		if (preg_match('!^SELECT!i', $sql)) {
			$this->cache = true;
			$md5 = md5($sql).'.cache';
			$this->file = CACHE.DS.'models'.DS.$this->model.DS.$md5;
			if(!$this->cache_force && file_exists($this->file)) {
				$ctime = filemtime($this->file)+$this->cache_time;
				$ftime = time();
				if($ctime >= $ftime) {
					$this->cache_db = unserialize(@file_get_contents($this->file));
					return;
				}
			} 
			return parent::query($sql);
		}
		$this->cache = false;
		return parent::query($sql);
	}
	
	function query_save($data) {
		if(!is_dir(CACHE.DS.'models'.DS.$this->model)) {
			@mkdir(CACHE.DS.'models'.DS.$this->model, 0777);
		}
		save_file($this->file,serialize($data));
	}
	
	function fetch_row($assoc = true) {
		if($this->cache_db) {
			return $this->cache_db;
		} else {
			$row = parent::fetch_row($assoc);
			if($this->cache) {
				$this->query_save($row);
			}
			return $row;
		}
	}
	
	function fetch_rows($assoc = true) {
		if($this->cache_db) {
			return $this->cache_db;
		} else {
			$rows = array();
			while($row = parent::fetch_row($assoc)) $rows[] = $row;
			if($this->cache) {
				$this->query_save($rows);
			}
			return $rows;
		}
	}
	
	function last_num_rows() {
		if($this->cache_db) {
			if(is_numeric($cache[0])) return $cache[0];
			else return count($cache);
		} else {
			$row = parent::last_num_rows($this->id_query);
			if($this->cache) {
				$this->query_save(array($row));
			}
			return $row;
		}
    }
	
}

?>